/**
 * 用户管理模块
 */

const router = require('koa-router')()
const User = require('./../models/userScheme')
const Counter = require('./../models/counterScheme')
const util = require('./../utils/util')
const jwt = require('jsonwebtoken')
const md5 = require('md5')

router.prefix('/users')
// 用户登录
router.post('/login', async (ctx) => {
  try {
    const {
      userName,
      userPwd
    } = ctx.request.body
    const res = await User.findOne({
      userName,
      userPwd
    }, 'userId userName userEmail state role deptId roleList')
    // 获取res中数据库里的信息
    const data = res._doc
    // token加密
    const token = jwt.sign({
      data
    }, 'iloveu', {
      expiresIn: 3000
    })
    if (res) {
      data.token = token
      ctx.body = util.success(data)
    } else {
      ctx.body = util.fail("账号或密码不正确", '')
    }
  } catch (error) {
    ctx.body = util.fail(`数据库异常${error.stack}`)
  }

})
// 获取用户列表
router.get('/list', async (ctx) => {
  const {
    userId,
    userName,
    state
  } = ctx.request.query
  const {
    page,
    skipIndex
  } = util.paper(ctx.request.query)
  let params = {}
  if (userId) params.userId = userId
  if (userName) params.userName = userName
  if (state && state != '0') params.state = state
  try {
    // 根据条件查询
    const list = await User.find(params, {
      _id: 0,
      userPwd: 0
    }).skip(skipIndex).limit(page.pageSize)
    const total = await User.countDocuments(params);
    ctx.body = util.success({
      page: {
        ...page,
        total
      },
      list
    })
  } catch (error) {
    ctx.body = util.fail(`查询异常：${error.stack}`)
  }
})

// 用户单个/批量删除
router.post('/delete', async (ctx) => {
  const {
    userids
  } = ctx.request.body
  console.log(userids);
  try {
    // const res = await User.updateMany({userId: {$in: userIds}}, {state: 2})
    const res = await User.updateMany({
      userId: {
        $in: userids
      }
    }, {
      state: 2
    })
    if (res.modifiedCount > 0) {
      ctx.body = util.success(res, `共删除成功${res.modifiedCount}条`)
      return
    }
    ctx.body = util.fail('删除失败')
  } catch (error) {
    ctx.body = util.fail(`查询异常：${error.stack}`)
  }


})

// 用户新增/编辑
router.post('/operate', async (ctx) => {
  const {
    userId,
    userName,
    mobile,
    userEmail,
    job,
    deptId,
    state,
    roleList,
    action
  } = ctx.request.body
  if (action == 'add') {
    // 新增
    if (!userName || !userEmail || !deptId) {
      ctx.body = util.fail('参数错误', util.CODE.PARAM_ERROR)
      return
    }
    const res = await User.findOne({ $or: [{ userName }, { userEmail }] }, '_id userName userEmail')
    if (res) {
      ctx.body = util.fail(`系统监测到有重复的用户，信息如下：${res.userName} - ${res.userEmail}`)
    } else {
      const doc = await Counter.findOneAndUpdate({ _id: 'userId' }, { $inc: { sequence_value: 1 } }, { new: true })
      console.log(doc);
      try {
        const user = new User({
          userId: doc.sequence_value,
          userName,
          userPwd: md5('123456'),
          userEmail,
          role: 1, //默认普通用户
          roleList,
          job,
          state,
          deptId,
          mobile
        })
        user.save();
        ctx.body = util.success({}, '用户创建成功');
      } catch (error) {
        ctx.body = util.fail(error.stack, '用户创建失败');
      }
    }
  } else {
    // 编辑
    if (!deptId) {
      ctx.body = util.fail('部门不能为空', util.CODE.PARAM_ERROR)
      return
    }
    try {
      const res = await User.findOneAndUpdate({ userId }, { mobile, job, state, roleList, deptId, })
      ctx.body = util.success({}, '更新成功')
    } catch (error) {
      ctx.body = util.fail(error.stack, '更新失败')
    }
  }

})
module.exports = router